package com.itheima.web.controller.store;

import com.github.pagehelper.PageInfo;
import com.itheima.core.BaseServlet;
import com.itheima.domain.store.Company;
import com.itheima.service.store.impl.CompanyServiceImpl;
import com.itheima.utils.BeanUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/store/company/*")
public class CompanyServlet extends BaseServlet {
    private CompanyServiceImpl cs = new CompanyServiceImpl();

    public String list(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");

        if (StringUtils.isBlank(pageNum)) {
            pageNum = "1";
        }
        if (StringUtils.isBlank(pageSize)) {
            pageSize = "10";
        }
        PageInfo<Company> pageInfo = cs.queryPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        request.setAttribute("page", pageInfo);
        return "/WEB-INF/pages/store/company/list.jsp";
    }

    public String toAdd(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return "/WEB-INF/pages/store/company/add.jsp";
    }

    public String save(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Company company = BeanUtil.fillBean(request, Company.class, "yyyy-MM-dd");
        cs.save(company);
        return "/store/company/list";
    }

    public String toEdit(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        Company company = cs.findById(id);
        request.setAttribute("company", company);
        return "/WEB-INF/pages/store/company/update.jsp";
    }

    public String edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Company company = BeanUtil.fillBean(request, Company.class, "yyyy-MM-dd");
        cs.update(company);
        return "/store/company/list";
    }

    public String delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String[] ids = request.getParameterValues("id");
        cs.deleteById(ids);
        return "/store/company/list";
    }
}
